package com.meme.editor.model.sprite2d;

import org.apache.log4j.Logger;

import com.meme.editor.EntityRefLink;

public class Tiled2dLayer extends Tiled2dGrid 
{
	static Logger logger = Logger.getLogger (Tiled2dLayer.class);
	
	public static final int DefaultCellWidth = 16;
	public static final int DefaultCellHeight = 16;
	

	public static final int MaxCellRows = 1000;
	public static final int MaxCellCols = 1000;
	


	
	Tiled2dLayerCell[][] mLayerCells;
	
	public Tiled2dLayer ()
	{
		this (DefaultCellWidth, DefaultCellHeight, 50, 50);
	}
	
	public Tiled2dLayer (int cellWidth, int cellHeight, int cellRows, int cellCols)
	{
		super (cellWidth, cellHeight, cellRows, cellCols);
	}
	
	public Tiled2dLayerCell getLayerCellByName (String name)
	{
		// return (Tiled2dModule) getChildByName(name);
		
		int _pos = name.indexOf(',');
		int cellRow = Integer.parseInt(name.substring(0, _pos));
		int cellCol = Integer.parseInt(name.substring(_pos + 1));
		
		return getLayerCellByPos (cellRow, cellCol);
	}
	
	public Tiled2dLayerCell getLayerCellByIndex (int index)
	{
		int cellRow = index / getCellCols ();
		int cellCol = index - cellRow * getCellCols ();
		return getLayerCellByPos (cellRow, cellCol);
	}
	
	public Tiled2dLayerCell getLayerCellByPos (int cellRow, int cellCol)
	{
		return mLayerCells [cellRow][cellCol];
	}
	
	@Override
	public String getDefaultName ()
	{
		return "Tiled Layer";
	}
	
	@Override int getMaxCellRows () {return MaxCellRows;}
	@Override int getMaxCellCols () {return MaxCellCols;}
	
	@Override
	protected void handleGridSizeChanged (int oldRows, int oldCols)
	{
		Tiled2dLayerCell[][] oldCells = mLayerCells;
		
		mLayerCells = new Tiled2dLayerCell[mCellRows][mCellCols];
		
		for (int row = 0; row < oldRows; ++ row)
		{
			for (int col = 0; col < oldCols; ++ col)
			{
				if ( row >= mCellRows || col >= mCellCols )
					oldCells[row][col].setModule(null);
			}
		}
		
		for (int row = 0; row < mCellRows; ++ row)
		{
			for (int col = 0; col < mCellCols; ++ col)
			{
				if (row < oldRows && col < oldCols)
				{
					mLayerCells[row][col] = oldCells[row][col];
				}
				else
				{
					mLayerCells[row][col] = new Tiled2dLayerCell (this);
				}
			}
		}
	}
}
